<template>
  <view class="container">
    <!-- 固定头部 -->
    <uni-nav-bar
      dark
      :fixed="true"
      shadow
      background-color="#007AFF"
      status-bar
      title="浙享物联-设备监控"
    />
    <view class="box-header">
      <view class="box-bg">
        <view class="input-view">
          <uni-icons
            class="input-uni-icon"
            type="search"
            size="18"
            color="#999"
          />
          <input
            confirm-type="search"
            class="nav-bar-input"
            v-model="searchParm.deviceName"
            type="text"
            placeholder="输入搜索关键词"
          />
        </view>
        <view class="right-view" v-if="checkPermission(['device:search'])">
          <button
            class="button"
            @click="handleSearch"
            hover-class="button-hover"
          >
            搜索
          </button>
        </view>
        <view class="right-view" v-if="checkPermission(['device:add'])">
          <button class="button" @click="handleAdd" hover-class="button-hover">
            添加
          </button>
        </view>
      </view>
      <view class="box-bg2">
        <uni-data-select
          v-model="searchParm.deviceType"
          :localdata="getSelectList('mqtt_device_type')"
          @change="change"
          placeholder="分组"
          style="width: 50%; height: 30rpx !important"
        ></uni-data-select>
        <uni-data-select
          v-model="searchParm.isOnline"
          :localdata="getSelectList('mqtt_config_online')"
          @change="change"
          placeholder="是否在线"
          style="width: 50%; height: 30rpx !important"
        ></uni-data-select>
      </view>
    </view>
    <!--  -->
    <scroll-view
      class="scrollable-content"
      scroll-y="true"
      @scrolltolower="onLoadMore"
      @refresherrefresh="onRefresh"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      refresher-background="#f0f0f0"
      refresher-threshold="80"
      :style="{ height: scrollViewHeight + 'px' }"
    >
      <view class="card-view" v-for="item in data" :key="item.id">
        <uni-swipe-action>
          <uni-swipe-action-item
            :right-options="getRightOptions(item)"
            @click="showMap(item)"
          >
            <view class="card-content" @click="cardClick(item)">
              <view class="card-top">
                <image class="card-image" :src="baseURL + item.picUrl"> </image>
                <view class="card-info">
                  <view class="card-info-item">
                    <text class="card-text1">{{ item.deviceName }} </text>
                  </view>
                  <view class="card-info-item">
                    <uni-tag
                      :text="item.isOnline == '1' ? '在线' : '离线'"
                      size="mini"
                      :type="item.isOnline == '1' ? 'success' : 'error'"
                      custom-style="padding: 1rpx 8rpx !important; font-size: 16rpx !important; margin-right: 5rpx;"
                    >
                    </uni-tag>

                    <uni-tag
                      :text="
                        getLabel('mqtt_device_networktype', item.networkType)
                      "
                      size="mini"
                      type="primary"
                      custom-style="padding: 1rpx 8rpx !important; font-size: 16rpx !important;"
                    >
                    </uni-tag>
                  </view>
                  <view class="card-info-item">
                    <uni-icons type="location-filled" size="17"></uni-icons>
                    <text class="card-text card-text3">{{ item.address }}</text>
                  </view>
                </view>
              </view>

              <view class="card-down">
                <view class="card-text">
                  余氯: <text class=" ">{{ item.yl }} mg/L</text>
                </view>
                <view class="card-text">
                  <!-- 温度:<text class="error">{{ item.wd }}</text> -->
                  温度: <text class=" ">{{ item.wd }} ℃</text>
                </view>
                <view class="card-text">
                  浊度: <text class=" ">{{ item.zd }} NTU</text>
                </view>
                <view class="card-text">
                  pH: <text class=" ">{{ item.ph }} pH</text>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>

      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="loading">
        <uni-load-more
          status="loading"
          :content-text="loadingText"
        ></uni-load-more>
      </view>

      <!-- 没有更多数据提示 -->
      <view class="loading-more" v-if="!hasMore && data && data.length > 0">
        <uni-load-more
          status="noMore"
          :content-text="noMoreText"
        ></uni-load-more>
      </view>

      <!-- 空数据提示 -->
      <view class="empty-data" v-if="!loading && (!data || data.length === 0)">
        <text class="empty-text">暂无数据</text>
      </view>
    </scroll-view>
    <MapPopup
      :visible="mapVisible"
      :longitude="currentDevice.longitude"
      :latitude="currentDevice.latitude"
      @close="mapVisible = false"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import uniDataSelect from "@dcloudio/uni-ui/lib/uni-data-select/uni-data-select.vue";
import { getPageList, getDeviceImage } from "@/api/index";
import type { DeviceVO } from "@/types/login";
import { config } from "@/config";
import MapPopup from "@/pages/index/MapPopup.vue";
import uniSwipeAction from "@dcloudio/uni-ui/lib/uni-swipe-action/uni-swipe-action.vue";
import uniSwipeActionItem from "@dcloudio/uni-ui/lib/uni-swipe-action-item/uni-swipe-action-item.vue";
import { getSelectList, getLabel } from "@/utils/wxdict";
import { usePermission } from "@/utils/permission";
const { checkPermission } = usePermission();

const baseURL = config.baseUrl + "/cert/";

const value = ref("");

// 分页相关状态
const searchParm = ref({
  deviceName: "",
  deviceType: "",
  isOnline: "",
  pageNo: 1,
  pageSize: 5,
});

// 加载状态
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);
const scrollViewHeight = ref(0);

// 加载提示文本
const loadingText = {
  contentdown: "上拉显示更多",
  contentrefresh: "正在加载...",
  contentnomore: "没有更多数据了",
};

const noMoreText = {
  contentdown: "上拉显示更多",
  contentrefresh: "正在加载...",
  contentnomore: "没有更多数据了",
};

const change = (e: any) => {
  console.log(e);
};

// 重置搜索参数
const resetSearchParams = () => {
  searchParm.value.pageNo = 1;
  hasMore.value = true;
};

// 搜索处理
const handleSearch = async () => {
  resetSearchParams();
  await loadData();
};

// 加载数据
const loadData = async (isLoadMore = false) => {
  if (loading.value) return;

  loading.value = true;

  try {
    const res = await getPageList(searchParm.value);

    if (isLoadMore) {
      // 加载更多，追加数据
      if (res.data.list && res.data.list.length > 0) {
        data.value = [...(data.value || []), ...res.data.list];
        searchParm.value.pageNo++;
      } else {
        hasMore.value = false;
      }
    } else {
      // 首次加载或刷新，替换数据
      data.value = res.data.list || [];
      searchParm.value.pageNo = 1;
      hasMore.value =
        res.data.list && res.data.list.length >= searchParm.value.pageSize;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  resetSearchParams();
  await loadData();
};

// 上拉加载更多
const onLoadMore = async () => {
  if (!hasMore.value || loading.value) return;
  await loadData(true);
};

const data = ref<DeviceVO[]>();
const mapVisible = ref(false);
const currentDevice = ref<DeviceVO>({
  longitude: 0,
  latitude: 0,
} as DeviceVO);

// 计算滚动区域高度
const calculateScrollViewHeight = () => {
  const systemInfo = uni.getSystemInfoSync();
  const navBarHeight = 44; // 导航栏高度
  const headerHeight = 130; // 头部搜索区域高度
  const statusBarHeight = systemInfo.statusBarHeight || 0;
  scrollViewHeight.value =
    systemInfo.windowHeight -
    navBarHeight -
    headerHeight -
    statusBarHeight +
    50;
};

onLoad(async () => {
  const hasp = checkPermission(["device:search"]);
  if (!hasp) {
    uni.showToast({
      title: "无权限",
      icon: "none",
    });
    return;
  }

  // 计算滚动区域高度
  calculateScrollViewHeight();
  // 加载初始数据
  await loadData();
});

onMounted(() => {
  // 监听窗口大小变化
  uni.onWindowResize(() => {
    calculateScrollViewHeight();
  });
});

const showMap = (device: DeviceVO) => {
  if (device.longitude && device.latitude) {
    currentDevice.value = device;
    mapVisible.value = true;
  } else {
    uni.showToast({
      title: "设备位置信息不完整",
      icon: "none",
    });
  }
};

const cardClick = (item: DeviceVO) => {
  uni.navigateTo({
    url: `/pagesS1/device-info/index?deviceId=${item.id}&deviceKey=${item.deviceKey}&deviceName=${item.deviceName}`,
  });
};

const handleAdd = () => {
  uni.navigateTo({
    url: "/pagesS1/device-info/devi-add",
  });
};

const getRightOptions = (item: DeviceVO) => {
  const options = [];
  // 只有有地图权限时才显示地图选项
  if (checkPermission(["device:mp"])) {
    options.push({
      text: "地图",
      style: {
        backgroundColor: "#007AFF",
      },
    });
  }
  return options;
};

const getImageUrl = (item: DeviceVO) => {
  return getDeviceImage(item.id);
};
</script>

<style lang="scss" scoped>
$nav-height: 35px;
.box-bg {
  background-color: #fff;
  height: 90rpx;
  padding: 0rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  align-content: center;
  margin: 0rpx 20rpx;
  .button {
    background-color: #007aff;
    color: #fff;
    border-radius: 5px;
    margin-left: 0px;
    font-size: 20rpx;
    width: 100rpx;
    height: 60rpx;
    line-height: 60rpx;
    margin-right: 5rpx;
  }

  .button-hover {
    background-color: #0051aa;
    transform: scale(0.98);
  }
}

.box-bg2 {
  background-color: #fff;
  height: 40rpx;
  padding: 0rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  align-content: center;
  margin: 10rpx 20rpx;
  margin-top: 1rpx;
  .uni-select {
    height: 30px !important;
  }
}

.scrollable-content {
  margin-top: 40rpx; /* 根据固定头部的高度调整 */
  background-color: #f5f5f5;
}

.loading-more {
  padding: 20rpx;
  text-align: center;
}

.empty-data {
  padding: 100rpx 20rpx;
  text-align: center;
  .empty-text {
    color: #999;
    font-size: 28rpx;
  }
}

.input-view {
  display: flex;
  flex-direction: row;
  flex: 1;
  background-color: #f8f8f8;
  height: $nav-height;
  border-radius: 15px;
  padding: 0 15px;
  flex-wrap: nowrap;
  margin: 7px 0;
  line-height: $nav-height;
}

.input-uni-icon {
  line-height: $nav-height;
}

.nav-bar-input {
  height: $nav-height;
  line-height: $nav-height;
  width: 350rpx;
  padding: 0 5px;
  font-size: 12px;
  background-color: #f8f8f8;
}

.card-view {
  margin: 15rpx 20rpx 10rpx 20rpx;
  box-sizing: border-box;
  background-color: #ffffff;
  border-radius: 15rpx;
  border: 1px solid rgb(239 231 231);
  box-shadow: 1rpx 3rpx 1rpx 0rpx #e6eaf1;
  .card-top {
    width: 100%;
    height: 200rpx;
    display: flex;
    justify-content: flex-start;
    align-items: left;
    align-content: center;
    .card-image {
      width: 180rpx;
      height: 180rpx;
      border-radius: 10rpx;
      margin: 20rpx;
    }

    .card-info {
      position: relative;
      height: 180rpx;
      width: calc(100% - 180rpx - 80rpx);
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      align-items: left;
      align-content: center;
      font-size: 18rpx;
      margin: 20rpx;
      .card-info-item {
        color: #ffffff;
        font-size: 20rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        v::deep .uni-tag--mini {
          padding: 1px 10px !important;
          font-size: 10px !important;
          border-radius: 2px;
        }
      }

      .card-text {
        margin-right: 10rpx;
      }
      .card-text1 {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        line-height: 40rpx;
        max-width: 100%;
        word-wrap: break-word;
        white-space: normal;
      }

      .card-text2 {
        font-size: 24rpx;
        color: #666;
        line-height: 1;
      }
      .card-text3 {
        gap: 5rpx;
        font-size: 24rpx;
        color: #666;
        line-height: 1;
      }
    }
  }
  .card-down {
    width: 100%;
    height: 50rpx;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    align-content: center;
    .card-text {
      font-size: 20rpx;
      color: #666;
      line-height: 1;
    }
    .green {
      color: #4caf50; /* 绿色 */
    }
    .yellow {
      color: #ffd700; /* 黄色 */
    }
    .error {
      color: #e04609; /* 红色 */
    }
  }
}

.card-content {
  width: 100%;
}
</style>

